<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Cron extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('csvparser');
        $this->load->library('download');
    }

    private function downloadData($arrSymbol, $cnx_symbols, $startdate, $enddate)
    {
        $aCurlInfo = array();
        $oDownload = new Download();
        $oDownload->setAgent($this->getAgent());

        //setup curl data
        foreach ($arrSymbol as $item) {
            $sym = $item;
            $sym = $this->encodeURL($sym);
            $aInfo = array();
            $aInfo['symbol'] = $item;
            if (in_array($item, $cnx_symbols)) {
                $aInfo['remark'] = false;
                $aInfo['url'] = CSV_HOST_CNX;
                $aInfo['queryString'] = $sym . $startdate->format('d-m-Y') . '-' . $startdate->
                    format('d-m-Y') . TEMP_CSV_FILE_EXT;
            } else {
                $aInfo['remark'] = true;
                $aInfo['url'] = CSV_HOST;
                $aInfo['queryString'] = "symbol={$sym}&fromDate={$startdate->format('d-M-Y')}&toDate={$enddate->format('d-M-Y')}&datePeriod=unselected&hiddDwnld=true";
            }
            array_push($aCurlInfo, $aInfo);
        }
        return $oDownload->exec($aCurlInfo);
    }

    public function index()
    {
        $this->load->model('repos/symbolmodel', 'SymbolModel');
        $aSymbol = $this->SymbolModel->getSymbol();

        //check if have symbol
        if (count($aSymbol) <= 0) {
            show_error(NO_SYMBOL_FOUND . ' !');
        }

        //download
        $aSymbolEntity = array();
        $aErrorSymbol = array();
        $cnx_symbols = unserialize(CNX_SYMBOLS);

        //set date
        $startdate = new DateTime('now', new DateTimeZone(TIMEZONE));
        $enddate = $this->getDateForCron($startdate, 1);
        $arrSymbol = array();
        foreach ($aSymbol as $a) {
            array_push($arrSymbol, $a->getUrlVal());
        }

        //download data
        $aReturnData = $this->downloadData($arrSymbol, $cnx_symbols, $startdate, $enddate);

        //check for error symbols downloaded
        $aErrorSymbol = array_diff($arrSymbol, $aReturnData);

        //get array symbols details
        $aSymbolDetails = array();
        if (!empty($aErrorSymbol)) {
            $aSymbolDetails = $this->SymbolModel->getArraySymbolDetails($aReturnData);
        } else {
            $aSymbolDetails = $aSymbol;
        }

        //parse to entity
        foreach ($aSymbolDetails as $sSymbold) {
            $filePath = TEMP_CSV_PATH . $sSymbold->getUrlVal() . TEMP_CSV_FILE_EXT;
            $aData = array();
            if (in_array($sSymbold->getUrlVal(), $cnx_symbols)) {
                $aData = $this->csvparser->parserToEntity2($sSymbold->getId(), $filePath);
            } else {
                $aData = $this->csvparser->parserToEntity($sSymbold->getId(), $filePath);
            }
            if (!empty($aData)) {
                $aSymbolEntity = array_merge($aSymbolEntity, $aData);
            } else {
                if (!in_array($sSymbold->getUrlVal(), $aErrorSymbol)) {
                    array_push($aErrorSymbol, $sSymbold->getUrlVal());
                }
            }
            unlink($filePath);
        }

        $result = $this->SymbolModel->insertCompanyDetailsForCron($aSymbolEntity, $startdate,
            $enddate);
        if ($result > 0 && count($aErrorSymbol) == 0) {
            echo "<span class='success'>Save symbols data successful !</span>";
        } else {
            echo "<span class='error'>Save symbol <strong>" . implode(', ', $aErrorSymbol) .
                "</strong> data failed !</span>";
        }
        return;
    }

    private function getDateForCron($date = null, $nextCountDays = null)
    {
        if ($nextCountDays != null) {
            $d = $date->format('Y-m-d H:i:s');
            $nextDate = date('Y-m-d H:i:s', strtotime("$d {$nextCountDays} days"));
            return new DateTime($nextDate, new DateTimeZone(TIMEZONE));
        }
        $time = new DateTime('now', new DateTimeZone(TIMEZONE));
        return $time;
    }
}
?>